package com.fa.wisdom.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.coder.zzq.smartshow.dialog.LoadingDialog;
import com.fa.wisdom.R;
import com.fa.wisdom.base.BaseActivity;
import com.fa.wisdom.base.Constant;
import com.fa.wisdom.common.App;
import com.fa.wisdom.model.ResultEntity;
import com.fa.wisdom.net.MyCallback;
import com.fa.wisdom.net.Task;
import com.fa.wisdom.utils.BitmapCompressUtils;
import com.fa.wisdom.utils.FileUtils;
import com.fa.wisdom.utils.ImRezUtils;
import com.fa.wisdom.utils.Loading;
import com.fa.wisdom.utils.PermissionUtils;
import com.fa.wisdom.utils.SpUtils;
import com.fa.wisdom.utils.TitleBuilder;
import com.fa.wisdom.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.List;

import me.shaohui.bottomdialog.BottomDialog;
import okhttp3.Call;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

public class UserInfoActivity extends BaseActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {
    public static final int TAKE_PHOTO_CODE = 112;
    public static final int PICK_PHOTO_CODE = 113;
    ImageView civ_head;
    TextView name, sex, age, phone;


    private final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,//存储权限
            Manifest.permission.READ_EXTERNAL_STORAGE};
    RelativeLayout rel_resetPwd;

    @Override
    public void setListen() {
        civ_head = findViewById(R.id.civ_head);
        name = findViewById(R.id.tv_name);
        sex = findViewById(R.id.tv_sex);
        age = findViewById(R.id.tv_age);
        phone = findViewById(R.id.tv_phone);
        civ_head.setOnClickListener(this);
        new TitleBuilder(this).setTitleText("个人资料")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    }

    /**
     * 获取相关权限
     */
    private void getPermission() {
        if (EasyPermissions.hasPermissions(this, PERMISSIONS)) {
            //已经打开权限
            showSelectDialog();
        } else {
            //没有打开相关权限、申请权限
            EasyPermissions.requestPermissions(this, "需要获取您的相册、相机使用权限，否则将无法进行修改图像！", 1, PERMISSIONS);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //回调结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (perms.size() == 3) {
            showSelectDialog();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ToastUtils.showError("权限已被拒绝，请手动在设置里面打开权限");
    }

    /**
     * 选择照片弹窗
     */
    String APP_DIR = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + "wisdom";

    private void showSelectDialog() {
        final BottomDialog bottomDialog;
        bottomDialog = BottomDialog.create(this.getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                //照相
                v.findViewById(R.id.tv_takephoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (PermissionUtils.getInstance().checkPermission(App.getContext(),
                                Manifest.permission.CAMERA)) {
                            File myhead = new File(APP_DIR + "/head.jpg");
                            Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri uri = FileProvider.getUriForFile(App.getContext(),
                                    getPackageName() + ".fileprovider", myhead);
                            it.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(it, PICK_PHOTO_CODE);
                        } else {
                            PermissionUtils.getInstance().showSystemPermissionsSettingDialog(UserInfoActivity.this);
                        }
                        bottomDialog.dismiss();
                    }
                });
                //选择照片
                v.findViewById(R.id.tv_selectphoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent(Intent.ACTION_PICK, null);
                        it.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(it, TAKE_PHOTO_CODE);
                        bottomDialog.dismiss();
                    }
                });

                //取消
                v.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bottomDialog.dismiss();
                    }
                });

            }
        }).setLayoutRes(R.layout.select_change_image)
                .setDimAmount(0.4f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                .setCancelOutside(true)     // click the external area whether is closed, default is : true
                .setTag("BottomDialog")     // setting the DialogFragment tag
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择图片
        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            try {
                if (data.getData() != null) {
                    //TODO

                    String path = FileUtils.getFilePath(this, data.getData());//图片路径
//                    String path = "storage/emulated/0/Pictures/Screenshots/"+System.currentTimeMillis()+".jpg";//图片路径
                    Log.e("test-data", "onActivityResult: " + path);
                    Bitmap bm = null;
                    ///storage/emulated/0/Pictures/Screenshots/Screenshot_20190123-214734.jpg
                    File file = new File(path);
                    if (file.exists()) {
                        bm = BitmapFactory.decodeFile(FileUtils.getFilePath(this, data.getData()));
                        bm = BitmapCompressUtils.imageZoom(bm, 50);
                        file = ImRezUtils.saveBitmapFile(bm, path);
                    }
                    //上传图片
                    if (FileUtils.getFilePath(this, data.getData()) != null) {
                        // TODO 上传服务器
                        ToastUtils.showError(path);
                        SpUtils.getInstance().encode("head", path);
                        civ_head.setImageBitmap(bm);
//                        upLoadFile(file, bm);
                        uploadImg(file);
                    } else {
                        ToastUtils.showError("文件不存在！");
                    }
                } else {
                    ToastUtils.showError("获取数据为空！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        //拍照
        if (requestCode == PICK_PHOTO_CODE && resultCode == RESULT_OK) {
            try {
                String path = APP_DIR + "/head.jpg";
                File temp = new File(path);
                if (temp.exists()) {
                    // TODO 上传服务器
                    Bitmap bm = BitmapFactory.decodeFile(APP_DIR + "/head.jpg");
                    bm = BitmapCompressUtils.imageZoom(bm, 50);
                    temp = ImRezUtils.saveBitmapFile(bm, path);
                    ToastUtils.showError(path);
                    SpUtils.getInstance().encode("head", path);
                    civ_head.setImageBitmap(bm);
//                    upLoadFile(temp, bm);
                    uploadImg(temp);
                } else {
                    ToastUtils.showError("文件不存在！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void setTitleBarColor() {

    }

    @Override
    protected boolean isStatusBarBlack() {
        return true;
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_user_info;
    }

    public void save(View view) {
        ToastUtils.showSuccess("保存成功");
    }

    @Override
    public void initView() {
        rel_resetPwd = findViewById(R.id.rel_resetPwd);
        rel_resetPwd.setOnClickListener(this);
    }

    @Override
    public void initData() {
        getUserInfo();
    }

    private void uploadImg(File file) {
        String token = SpUtils.getInstance().decodeString(Constant.TOKEN, "");
        OkHttpUtils.post().url("https://br.feiaikeji.cn/index.php/api/users/uplodfile")
                .addHeader("token", token)
                .addHeader("clientType", "android")
                .addFile("image", "head.jpg", file)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                e.printStackTrace();
                ToastUtils.showError("图像保存失败");
            }

            @Override
            public void onResponse(String response, int id) {
                ToastUtils.showSuccess("图像修改成功");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.civ_head:
                getPermission();
                break;
            case R.id.rel_resetPwd:
                startActivity(new Intent(this, ResetPwdActivity.class));
                break;
        }
    }

    private void getUserInfo() {
        LoadingDialog loadingDialog = Loading.getInstance().onShowLargeLoading("努力加载中...");
        loadingDialog.showInActivity(this);
        Task.getApiService().getUserInfo().enqueue(new MyCallback<ResultEntity>() {
            @Override
            protected void onSuccess(Response<ResultEntity> response) {
                loadingDialog.dismiss();
                String jsonString = JSON.toJSONString(response.body());
                JSONObject jsonObject = JSON.parseObject(jsonString);
                JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                String n = jsonObject1.getString("name");
                String head = jsonObject1.getString("avatarurl");
                String s = jsonObject1.getString("sex");
                String a = jsonObject1.getString("age");
                String p = jsonObject1.getString("phone");
                name.setText(n);
                sex.setText(s);
                age.setText(a);
                phone.setText(p);
                Glide.with(App.getContext()).load(TextUtils.isEmpty(head) ? R.drawable.mine_head : head)
                        .placeholder(R.drawable.mine_head)
                        .error(R.drawable.mine_head)
                        .into(civ_head);
            }

            @Override
            protected void onFailure(Throwable t) {
                loadingDialog.dismiss();
                ToastUtils.showError("获取用户信息失败");
            }
        });
    }
}
